home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c++ / 346 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.3 KB

  1. From: jodle@bix.com (jodle)
  2. Message-ID: <4fedrp$904@news2.delphi.com>
  3. X-Original-Date: 9 Feb 1996 03:08:41 GMT
  4. Path: in2.uu.net!bounce-back
  5. Date: 09 Feb 96 15:38:29 GMT
  6. Approved: fjh@cs.mu.oz.au
  7. Newsgroups: comp.std.c++
  8. Subject: Re: casting and virtual inheritence
  9. Organization: BIX
  10. References: <4fbt35$9ej@fido.asd.sgi.com> <4fdulf$34p@fsgm01.fnal.gov>
  11. X-Newsreader: TIN [version 1.2 PL2]
  12. X-Auth: PGPMoose V1.1 PGP comp.std.c++
  13.     iQBFAgUBMRtqhuEDnX0m9pzZAQFyBAF7BhSa4WGaejJBPrg3VpLGU1cYCFln0i4w
  14.     EEiPKq+iWZdZvlp+Xy2Z5DU2JjtNRhrk
  15.     =4pFN
  16.  
  17. David Sachs (b91926@fsgm01.fnal.gov) wrote:
  18. : First of all, I think (B*A) or dynamic_cast<B*>(A) is not a valid
  19. : expression, because A is a type name rather than a variable name. I
  20. : assume you meant dynamic_cast<B*>(a1)... In this case the semantics
  21. : are:
  22.  
  23. : class A {};
  24. : class B : public virtual A {};
  25.  
  26. : int main()
  27. : {
  28. :     A* a1 = new A;
  29. :     A* a2 = new B;
  30. :     B* b1 = dynamic_cast<B*>(a1);  // b1 == NULL, because there is no B
  31. :     B* b2 = dynamic_cast<B*>(a2);  // points to a2 as a B
  32. :     return 0;
  33. : }
  34.  
  35. I think the question "why?" remains unanswered.  The answer itself is
  36. quite simple.  If B virtually inherits A, each object instantiated from
  37. class B contains (or acts as if it contains) a pointer to the base class A
  38. part of itself.  It is not possible to downcast from an A to a B because
  39. we have no way of knowing for sure where the supposed B associated with A
  40. really is.  To illustrate, the data parts of our B might looks something
  41. like this: 
  42.  
  43. class B
  44.   {
  45.   A *virtualBaseClassA;
  46.   };
  47.  
  48. In contrast, if we have nonvirtual inheritance we (may, depending on the
  49. compiler) know that A and B both have the same address (but different
  50. sizes) in memory.  This looks something more like:
  51.  
  52. class B
  53.   {
  54.   A nonvirtualBaseClassA;
  55.   };
  56.  
  57. I don't view downcasting as the best thing to do, generally.  I have to
  58. say that the cast operators at least give us a way to do it that allows us
  59. to detect when the cast didn't work.  Without them, downcasting just gives
  60. you a pointer to some stuff that may or may not be what you think it
  61. should be.
  62. ---
  63. [ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  64.   Contact address: std-c++-request@ncar.ucar.edu.  Moderation policy:
  65.   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html. ]
  66.